package com.sea.demo.shiro.controller;

import com.sea.demo.shiro.domain.User;
import com.sea.demo.shiro.form.LoginForm;
import com.sea.demo.shiro.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @Author: 快乐在角落里
 * @Create: 2020/11/11 6:39
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    private final Logger LOGGER = LogManager.getLogger(LoginController.class);

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String login(@RequestBody LoginForm loginForm){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return "您已登录!";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(),loginForm.getPassword(),loginForm.isRememberMe());
        subject.login(token);
        User user = (User) subject.getPrincipal();

        // 修改登录时间
        user.setLastLoginTime(user.getLastLoginTime());
        user.setLoginTime(LocalDateTime.now());
        userService.update(user);
        LOGGER.info("LOGIN SUCCESS! --------- {}", user.getUsername());
        return "登录成功!";
    }
}
